import React, { useEffect, useRef, useState, useMemo } from "react";
// 确保导入对应的组件（根据你使用的UI库调整导入路径）

import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";

// 坐标有效性校验工具函数
const isCoordinateValid = (longitude, latitude) => {
  if (!longitude || !latitude) return false;
  const lng = Number(longitude);
  const lat = Number(latitude);
  if (isNaN(lng) || isNaN(lat)) return false;
  return lng >= -180 && lng <= 180 && lat >= -90 && lat <= 90;
};

// 跨越类型映射表
const crossingTypeMap = {
  powerLineOutagePlus500: "跨越电力线路（带电）",
  powerLineOutagePlus110: "  跨越电力线路（不带电）",
  railway: "跨越普通铁路",
  railwayHighSpeed: "跨越高铁",
  firstHighway: "跨越高速公路(含全封闭一级公路)",
  highwayGradePlus2: "跨越公路(二级及以下公路)",
  navigableRivers: "跨越通航河流",
  noNavigableRivers: "跨越不通航河流",
  railwayNormal: "跨越通信线路",
  other: "其它",
};

const CrossingPointsMap = ({ crossingPoints, projects }) => {
  // 地图容器及实例引用
  const mapContainer = useRef(null);
  const mapInstance = useRef(null);
  const tileLayer = useRef(null);
  const markerRefs = useRef({ crossingPoints: [], projects: [] });
  const scriptRef = useRef(null);
  const switchTimeout = useRef(null);

  // 状态管理（修复变量名不一致：isOffline → isOfflineMode）
  const [selectedCrossingFilter, setSelectedCrossingFilter] = useState("all");
  const [isOfflineMode, setIsOfflineMode] = useState(true); // 统一状态变量名
  const [mapLoaded, setMapLoaded] = useState(false);
  const [loadError, setLoadError] = useState("");
  const [isSwitching, setIsSwitching] = useState(false);

  // 过滤有效数据（保持不变）
  const validCrossingPoints = useMemo(() => {
    if (!crossingPoints || !Array.isArray(crossingPoints)) return [];
    return crossingPoints.filter((point) => {
      const isValid = isCoordinateValid(point.longitude, point.latitude);
      if (!isValid) console.warn("无效跨越点（已过滤）：", point);
      return isValid;
    });
  }, [crossingPoints]);

  const validProjects = useMemo(() => {
    if (!projects || !Array.isArray(projects)) return [];
    return projects.filter((project) => {
      const isValid = isCoordinateValid(project.longitude, project.latitude);
      if (!isValid) console.warn("无效项目点（已过滤）：", project);
      return isValid;
    });
  }, [projects]);

  const crossingFilterOptions = useMemo(() => {
    const uniqueNames = [
      ...new Set(
        validCrossingPoints.map((point) => point.name || "未命名跨越点")
      ),
    ];
    return [
      { value: "all", label: "全部跨越点" },
      ...uniqueNames.map((name) => ({ value: name, label: name })),
    ];
  }, [validCrossingPoints]);

  // 安全移除节点工具函数（保持不变）
  const safeRemoveChild = (parent, child) => {
    if (parent && child && parent.contains(child)) {
      try {
        parent.removeChild(child);
      } catch (e) {
        console.warn("移除节点失败：", e);
      }
    }
  };

  // 清除地图实例和脚本（保持不变）
  const cleanupMap = () => {
    if (switchTimeout.current) {
      clearTimeout(switchTimeout.current);
      switchTimeout.current = null;
    }

    markerRefs.current.crossingPoints.forEach((marker) => {
      try {
        marker.remove();
      } catch (e) {
        /* 忽略 */
      }
    });
    markerRefs.current.projects.forEach((marker) => {
      try {
        marker.remove();
      } catch (e) {
        /* 忽略 */
      }
    });
    markerRefs.current = { crossingPoints: [], projects: [] };

    if (mapInstance.current) {
      try {
        mapInstance.current.destroy();
      } catch (e) {
        console.warn("销毁地图实例时出错：", e);
      }
      mapInstance.current = null;
    }

    tileLayer.current = null;

    if (scriptRef.current) {
      safeRemoveChild(document.body, scriptRef.current);
      scriptRef.current = null;
    }

    if (window.AMap) {
      delete window.AMap;
      Object.keys(window).forEach((key) => {
        if (key.startsWith("AMap")) delete window[key];
      });
    }

    setMapLoaded(false);
    setLoadError("");
  };

  // 初始化地图（保持不变）
  const initMap = () => {
    if (!window.AMap) {
      setLoadError("未找到地图对象，请检查脚本");
      setIsSwitching(false);
      return;
    }

    console.log(`初始化${isOfflineMode ? "离线" : "在线"}地图`);
    const daLiCoordinates = [100.193681, 25.681281];
    const mapOptions = {
      zoom: 10,
      center: daLiCoordinates,
      resizeEnable: true,
      defaultCursor: "pointer",
      layers: [],
    };

    try {
      mapInstance.current = new window.AMap.Map(
        mapContainer.current,
        mapOptions
      );
    } catch (err) {
      console.error("地图实例创建失败：", err);
      setLoadError(`地图加载失败：${err.message}`);
      setIsSwitching(false);
      return;
    }

    if (isOfflineMode && window.AMap.TileLayer) {
      tileLayer.current = new window.AMap.TileLayer({
        getTileUrl: (x, y, z) => `/tile/${z}/${x}/${y}/tile.png`,
        zIndex: 1,
      });
      mapInstance.current.add(tileLayer.current);
    }

    if (window.AMap.ToolBar && window.AMap.Scale) {
      try {
        mapInstance.current.addControl(new window.AMap.Scale());
      } catch (e) {
        console.warn("添加控件失败：", e);
      }
    }

    mapInstance.current.on("complete", () => {
      console.log(`${isOfflineMode ? "离线" : "在线"}地图加载完成`);
      setMapLoaded(true);
      setIsSwitching(false);
      addCrossingPointMarkers();
      addProjectMarkers();
    });

    mapInstance.current.on("error", (err) => {
      const errorMsg = isOfflineMode
        ? `离线地图错误: ${err.message}`
        : `在线地图错误: 请检查API密钥和网络，${err.message}`;
      console.error(errorMsg);
      setLoadError(errorMsg);
      setMapLoaded(false);
      setIsSwitching(false);
    });
  };

  // 加载地图脚本（保持不变）
  const loadMapScript = () => {
    setIsSwitching(true);
    setMapLoaded(false);
    setLoadError("");
    cleanupMap();

    const script = document.createElement("script");
    script.type = "text/javascript";
    script.async = true;
    scriptRef.current = script;

    if (isOfflineMode) {
      script.src = "/amap/AMap3.js";
    } else {
      script.src =
        "https://webapi.amap.com/maps?v=1.4.15&key=1839e6aaba7a706de490affe43862708&plugin=AMap.ToolBar,AMap.Scale";
    }

    script.onerror = () => {
      const errorMsg = isOfflineMode
        ? "离线地图脚本加载失败，请检查本地文件"
        : "在线地图SDK加载失败，请检查网络";
      console.error(errorMsg);
      setLoadError(errorMsg);
      setIsSwitching(false);
    };

    script.onload = () => {
      if (window.AMap) {
        switchTimeout.current = setTimeout(initMap, 300);
      } else {
        setLoadError("未找到地图对象，请检查脚本");
        setIsSwitching(false);
      }
    };

    try {
      document.body.appendChild(script);
    } catch (e) {
      console.warn("添加脚本失败：", e);
      setLoadError("无法加载地图脚本");
      setIsSwitching(false);
    }
  };

  // 模式切换处理（修复变量名关联）
  const handleModeSwitch = (checked) => {
    setIsOfflineMode(checked); // 与状态变量保持一致
  };

  // 模式变化时重新加载（保持不变）
  useEffect(() => {
    if (mapContainer.current) loadMapScript();
  }, [isOfflineMode]);

  // 初始加载地图（保持不变）
  useEffect(() => {
    if (mapContainer.current) loadMapScript();
    return () => cleanupMap();
  }, []);

  // 标记点更新逻辑（保持不变）
  useEffect(() => {
    if (mapInstance.current && mapLoaded) {
      clearMarkers();
      addCrossingPointMarkers();
      addProjectMarkers();

      if (selectedCrossingFilter !== "all") {
        const targetPoint = validCrossingPoints.find(
          (point) => (point.name || "未命名跨越点") === selectedCrossingFilter
        );
        if (targetPoint) {
          mapInstance.current.setZoomAndCenter(10, [
            Number(targetPoint.longitude),
            Number(targetPoint.latitude),
          ]);
        }
      } else {
        const daLiCoordinates = [100.193681, 25.681281];
        mapInstance.current.setZoomAndCenter(10, daLiCoordinates);
      }
    }
  }, [validCrossingPoints, validProjects, selectedCrossingFilter, mapLoaded]);

  // 辅助方法（保持不变）
  const getProjectName = (projectId) => {
    const project = projects?.find((p) => p.id === projectId);
    return project ? project.projectName : "未知项目";
  };

  const addCrossingPointMarkers = () => {
    const filteredCrossings =
      selectedCrossingFilter === "all"
        ? validCrossingPoints
        : validCrossingPoints.filter(
            (point) => (point.name || "未命名跨越点") === selectedCrossingFilter
          );

    filteredCrossings.forEach((point) => {
      try {
        const marker = new window.AMap.Marker({
          position: [Number(point.longitude), Number(point.latitude)],
          title: point.name || "未命名跨越点",
          map: mapInstance.current,
          icon: new window.AMap.Icon({
            size: new window.AMap.Size(32, 32),
            image:
              "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
            imageSize: new window.AMap.Size(32, 32),
          }),
        });

        markerRefs.current.crossingPoints.push(marker);

        const infoWindow = new window.AMap.InfoWindow({
          content: `
            <div style="min-width: 200px; padding: 8px 0;">
              <h3 style="font-weight: 600; font-size: 16px; margin: 0 0 6px 0;">跨越点名称:${
                point.name
              }</h3>
              <p style="margin: 4px 0; font-size: 14px;">所属项目: ${getProjectName(
                point.projectId
              )}</p>
              <p style="margin: 4px 0; font-size: 14px;">跨越类型: ${
                crossingTypeMap[point.crossingType] || "未知"
              }</p>
              <p style="margin: 4px 0; font-size: 14px;">跨越对象: ${
                point.crossingObject
              }</p> 
              <p style="margin: 4px 0; font-size: 14px;">跨越点编号: ${
                point.code
              }</p>
            </div>
          `,
          offset: new window.AMap.Pixel(15, -10),
        });

        marker.on("click", () =>
          infoWindow.open(mapInstance.current, marker.getPosition())
        );
      } catch (e) {
        console.warn("创建勘察点标记失败：", e);
      }
    });
  };

  const addProjectMarkers = () => {
    validProjects.forEach((project, index) => {
      try {
        const marker = new window.AMap.Marker({
          position: [Number(project.longitude), Number(project.latitude)],
          title: project.name || `项目 ${index + 1}`,
          map: mapInstance.current,
          icon: new window.AMap.Icon({
            size: new window.AMap.Size(32, 32),
            image:
              "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
            imageSize: new window.AMap.Size(32, 32),
          }),
        });

        markerRefs.current.projects.push(marker);

        if (project.description || project.name) {
          const infoWindow = new window.AMap.InfoWindow({
            content: `
              <div style="padding: 10px;">
                <h3 style="margin: 0 0 5px 0; font-size: 16px;">${
                  project.name || `项目 ${index + 1}`
                }</h3>
                ${
                  project.description
                    ? `<p style="margin: 0; font-size: 14px;">${project.description}</p>`
                    : ""
                }
              </div>
            `,
            offset: new window.AMap.Pixel(0, 0),
          });

          marker.on("click", () =>
            infoWindow.open(mapInstance.current, marker.getPosition())
          );
        }
      } catch (e) {
        console.warn("创建项目点标记失败：", e);
      }
    });
  };

  const clearMarkers = () => {
    markerRefs.current.crossingPoints.forEach((marker) => {
      try {
        marker.remove();
      } catch (e) {
        /* 忽略 */
      }
    });
    markerRefs.current.projects.forEach((marker) => {
      try {
        marker.remove();
      } catch (e) {
        /* 忽略 */
      }
    });
    markerRefs.current = { crossingPoints: [], projects: [] };
  };

  // 渲染组件（优化Switch布局和样式）
  return (
    <div style={{ position: "relative", width: "100%", height: "100%" }}>
      {/* 控制面板 */}
      <div
        style={{
          position: "absolute",
          top: 10,
          right: 10,
          zIndex: 1001,
          width: "200px",
          padding: "12px", // 增加内边距，提升美观度
          backgroundColor: "white",
          borderRadius: "6px",
          boxShadow: "0 2px 10px rgba(0,0,0,0.1)", // 优化阴影
        }}
      >
        {/* 优化后的Switch区域 */}
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between", // 两端对齐，更美观
            marginBottom: "16px", // 与下方筛选器保持距离
            padding: "2px 0",
          }}
        >
          <Label
            htmlFor="offline-mode"
            style={{
              fontSize: "14px",
              color: isOfflineMode ? "#1890ff" : "#722ed1",
              cursor: "pointer",
              fontWeight: 500, // 稍微加粗，提升可读性
            }}
          >
            {isOfflineMode ? "离线模式" : "在线模式"} {/* 动态显示模式文本 */}
          </Label>
          <Switch
            id="offline-mode"
            checked={isOfflineMode} // 关联正确的状态变量
            onCheckedChange={handleModeSwitch} // 关联切换函数
            aria-label={isOfflineMode ? "当前为离线模式" : "当前为在线模式"}
            style={{
              // 根据UI库调整，例如Chakra UI的Switch可通过colorScheme设置颜色
              colorScheme: isOfflineMode ? "blue" : "purple",
            }}
          />
        </div>

        {/* 跨越点筛选器（优化样式） */}
        <div style={{ marginTop: "8px" }}>
          <label
            style={{
              fontSize: "14px",
              color: "#666",
              display: "block", // 独占一行，更清晰
              marginBottom: "6px",
            }}
          >
            筛选跨越点：
          </label>
          <select
            value={selectedCrossingFilter}
            onChange={(e) => setSelectedCrossingFilter(e.target.value)}
            disabled={!mapLoaded || isSwitching}
            style={{
              width: "100%",
              padding: "6px 10px",
              border: "1px solid #ddd",
              borderRadius: "4px",
              fontSize: "14px",
              backgroundColor: "white",
              cursor: !mapLoaded || isSwitching ? "not-allowed" : "pointer",
              appearance: "none", // 去除默认下拉箭头样式
              backgroundImage:
                'url(\'data:image/svg+xml;charset=UTF-8,%3csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"%3e%3cpolyline points="6 9 12 15 18 9"%3e%3c/polyline%3e%3c/svg%3e\')',
              backgroundRepeat: "no-repeat",
              backgroundPosition: "right 8px center",
              backgroundSize: "16px",
            }}
          >
            {crossingFilterOptions.length > 1 ? (
              crossingFilterOptions.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))
            ) : (
              <option value="all" disabled>
                无有效跨越点数据
              </option>
            )}
          </select>
        </div>
      </div>

      {/* 错误提示（保持不变） */}
      {loadError && (
        <div
          style={{
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            zIndex: 999,
            backgroundColor: "rgba(255, 0, 0, 0.8)",
            color: "white",
            padding: "12px 20px",
            borderRadius: "4px",
            boxShadow: "0 2px 8px rgba(0,0,0,0.2)",
          }}
        >
          {loadError}
        </div>
      )}

      {/* 加载中提示（保持不变） */}
      {isSwitching && !loadError && (
        <div
          style={{
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            zIndex: 999,
            backgroundColor: "rgba(255, 255, 255, 0.8)",
            padding: "12px 20px",
            borderRadius: "4px",
            boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
          }}
        >
          {isOfflineMode ? "切换到离线地图..." : "切换到在线地图..."}
        </div>
      )}

      {/* 地图容器 */}
      <div ref={mapContainer} style={{ width: "100%", height: "100%" }} />
    </div>
  );
};

export default CrossingPointsMap;
